
import csv                      # 输出数据
import codecs                   # 防止乱码
import pandas as pd             # 读取数据
import time                     # 时间暂停，以免出现问题


import requests
import json

print("请输入API_KEY>>>")
API_key = input()
print("请输入SECRET_KEY>>>")
SECRET_key = input()
API_KEY = API_key
SECRET_KEY = SECRET_key
print("请输入源数据路径>>>")
data_name = input()
print("请输入目标数据路径>>>")
input_name = input()


def main():
    # 读取数据
    data_line = pd.read_csv(data_name)

    # 写入数据
    with codecs.open(input_name, "a", "utf-8-sig") as file:
        csv_writer = csv.writer(file)
        csv_writer.writerow(
            ["关键词", "时间", "博主", "内容", "点赞", "转发", "评论", "confidence", "negative_prob", "positive_prob", "sentiment"]
        )

        i = 0
        while data_line.iloc(0)[i][0]:
            try:
                url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=&access_token=" + get_access_token()

                payload = json.dumps(
                    {"text": data_line.iloc(0)[i][3]}
                )
                headers = {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }

                response = requests.request("POST", url, headers=headers, data=payload)

                # {"text":"你好","items":[{"confidence":0.940806,"negative_prob":0.0266372,"positive_prob":0.973363,"sentiment":2}],"log_id":1713499139684669215}
                # <class 'str'>
                parsed_data = json.loads(response.text)
                # {'confidence': 0.992045, 'negative_prob': 0.00357965, 'positive_prob': 0.99642, 'sentiment': 2}

                csv_writer.writerow(
                    [
                        data_line.iloc(0)[i][0],
                        data_line.iloc(0)[i][1],
                        data_line.iloc(0)[i][2],
                        data_line.iloc(0)[i][3],
                        data_line.iloc(0)[i][4],
                        data_line.iloc(0)[i][5],
                        data_line.iloc(0)[i][6],
                        parsed_data["items"][0]["confidence"],
                        parsed_data["items"][0]["negative_prob"],
                        parsed_data["items"][0]["positive_prob"],
                        parsed_data["items"][0]["sentiment"]
                    ]
                )
            except:
                print("{} tips has something wrong".format(i))
            time.sleep(0.2)
            print("{} tips has done".format(i))
            i += 1


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    main()
